import { createSlice } from '@reduxjs/toolkit'

const tabSlice = createSlice({
  name: 'tab',
  initialState: {
    isCollapse: false,
    tabsList: [
      {
        path: '/',
        name: 'home',
        label: '首页'
      }
    ],
    currentMenu: null
  },
  reducers: {
    collapseMenu: state => {
      state.isCollapse = !state.isCollapse
    },
    selectMenuList: (state, { payload: val }) => {
      if (val.name !== 'home') {
        state.currentMenu = val
        const result = state.tabsList.findIndex(item => item.name === val.name)
        if (result === -1) {
          state.tabsList = [...state.tabsList, val]  // 使用展开运算符
        }
      } else {
        state.currentMenu = null
      }
    },
    closeTab: (state, { payload: val }) => {
      const index = state.tabsList.findIndex(item => item.name === val.name)
      if (index !== -1) {
        state.tabsList = state.tabsList.filter((_, i) => i !== index)
      }
    },
    setCurrentMenu: (state, { payload: val }) => {
      state.currentMenu = val.name === 'home' ? null : val
    }
  }
})
export const { collapseMenu, selectMenuList, closeTab, setCurrentMenu } = tabSlice.actions
export default tabSlice.reducer